<?php
setlocale(LC_MONETARY, 'en_US');
require_once "../funciones.php";
require_once '../funciones/JSON.php';
autenticado();

$caweb = con_caweb();
$page = $_REQUEST['page']; // get the requested page
$limit = $_REQUEST['rows']; // get how many rows we want to have into the grid
$sidx = $_REQUEST['sidx']; // get index row - i.e. user click to sort
$sord = $_REQUEST['sord']; // get the direction
$examp = $_REQUEST["q"]; //query number
//recibe los parametros de la busqueda
$fecIni = $_REQUEST[fecIni];
$fecFin = $_REQUEST[fecFin];
$prove = $_REQUEST[prove];

//Valido los valores, si vienen vacios se manipulan para hacer la consulta
if ($fecIni == "")
    $fecIni = "1800-01-01";
if ($fecFin == "")
    $fecFin = "2888-12-31";
if ($prove != "")
    $sqlExt = " and pro.nit = '$prove' ";

if (!$sidx)
    $sidx = 1;


$wh = "";
$searchOn = Strip($_REQUEST['_search']);
if($searchOn=='true') {
	$searchstr = Strip($_REQUEST['filters']);
	$wh= constructWhere($searchstr);
//	echo $wh;
//        exit;
}
function constructWhere($s){
    $json = new Services_JSON();
    $qwery = "";
	//['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    $qopers = array(
				  'eq'=>" = ",
				  'ne'=>" <> ",
				  'lt'=>" < ",
				  'le'=>" <= ",
				  'gt'=>" > ",
				  'ge'=>" >= ",
				  'bw'=>" LIKE ",
				  'bn'=>" NOT LIKE ",
				  'in'=>" IN ",
				  'ni'=>" NOT IN ",
				  'ew'=>" LIKE ",
				  'en'=>" NOT LIKE ",
				  'cn'=>" LIKE " ,
				  'nc'=>" NOT LIKE " );
    if ($s) {
        $prueba = $json->decode($s);
        $jsona = objecto2array($prueba);
        //$jsona = json_decode($s,true);
        if(is_array($jsona)){
			$gopr = $jsona['groupOp'];
			$rules = $jsona['rules'];
            $i =0;
            foreach($rules as $key=>$val) {
                $field = $val['field'];
                $op = $val['op'];
                $v = $val['data'];
				if($v && $op) {
	                $i++;
					// ToSql in this case is absolutley needed
					$v = ToSql($field,$op,$v);
					if ($i == 1) $qwery = " AND ";
					else $qwery .= " " .$gopr." ";
					switch ($op) {
						// in need other thing
					    case 'in' :
					    case 'ni' :
					        $qwery .= $field.$qopers[$op]." (".$v.")";
					        break;
						default:
					        $qwery .= $field.$qopers[$op].$v;
					}
				}
            }
        }
    }
    return $qwery;
}

function objecto2array($object)
{
  if(is_array($object) || is_object($object))
  {
    $array = array();
    foreach($object as $key => $value)
    {
      $array[$key] = objecto2array($value);
    }
    return $array;
  }
  return $object;
}




function ToSql ($field, $oper, $val) {
	// we need here more advanced checking using the type of the field - i.e. integer, string, float
	switch ($field) {
		case 'id':
			return intval($val);
			break;
		case 'amount':
		case 'tax':
		case 'total':
			return floatval($val);
			break;
		default :
			//mysql_real_escape_string is better
			if($oper=='bw' || $oper=='bn') return "'" . addslashes($val) . "%'";
			else if ($oper=='ew' || $oper=='en') return "'%" . addcslashes($val) . "'";
			else if ($oper=='cn' || $oper=='nc') return "'%" . addslashes($val) . "%'";
			else return "'" . addslashes($val) . "'";
	}
}

switch ($examp) {
    case 1:
		$result = mysql_query("SELECT COUNT(*) AS count FROM cabeceras_oc cab
        inner join detalles_oc det on cab.transaccion = det.transaccion
        inner join proveedores pro on pro.nit = cab.proveedor
            WHERE estado <> 'A' and cab.fecha between '$fecIni' and '$fecFin' $sqlExt".$wh);
		$row = mysql_fetch_array($result,MYSQL_ASSOC);
		$count = $row['count'];

		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}
        if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
        if ($start<0) $start = 0;
        $SQL = "SELECT cab.transaccion as tran, cab.factura as factura, det.marca as marca, det.item as item, cab.oc as oc, cab.fecha as fecha, det.cantidad as cantidad, pro.nombre as proveedor, det.preciocompra,det.total, cab.sucursal as sucursal FROM cabeceras_oc cab
        inner join detalles_oc det on cab.transaccion = det.transaccion
        inner join proveedores pro on pro.nit = cab.proveedor
            WHERE estado <> 'A'  and cab.fecha between '$fecIni' and '$fecFin' $sqlExt".$wh." ORDER BY ".$sidx." ".$sord. " LIMIT ".$start." , ".$limit;
		$result = mysql_query( $SQL ) or die("Could not execute query 1.".mysql_error());
        //para el manejo de los totales
        $sql = "select sum(det.cantidad) as cantidad, sum(det.total) as valor FROM cabeceras_oc cab
        inner join detalles_oc det on cab.transaccion = det.transaccion
        inner join proveedores pro on pro.nit = cab.proveedor
            WHERE estado <> 'A'  and cab.fecha between '$fecIni' and '$fecFin' $sqlExt".$wh;
        $totales = mysql_query($sql, $caweb) or die("Couldn�t execute query." . mysql_error());
        $totales = mysql_fetch_array($totales, MYSQL_ASSOC);

if (stristr($_SERVER["HTTP_ACCEPT"], "application/xhtml+xml")) {
    header("Content-type: application/xhtml+xml;charset=utf-8");
} else {
    header("Content-type: text/xml;charset=utf-8");
}
$et = ">";
echo "<?xml version='1.0' encoding='utf-8'?$et\n";
echo "<rows>";
echo "<page>" . $page . "</page>";
echo "<total>" . $total_pages . "</total>";
echo "<records>" . $count . "</records>"; // be sure to put text data in CDATA$sql
echo "<userdata name='tcantidad'>".$totales['cantidad']."</userdata>";
echo "<userdata name='tvalor'>".money_format('%n',$totales['valor'])."</userdata>";
//echo "<sql>".$SQL."</sql>"; // be sure to put text data in CDATA
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "<row id='" . $row[tran] . "'>";
    echo "<cell>" . strtoupper($row[item]) . "</cell>";
    echo "<cell>" . strtoupper($row[marca]) . "</cell>";
    echo "<cell>" . strtoupper($row[oc]) . "</cell>";
    echo "<cell>" . strtoupper($row[factura]) . "</cell>";
    echo "<cell>" . strtoupper($row[fecha]) . "</cell>";
    echo "<cell>" . strtoupper($row[cantidad]) . "</cell>";
    echo "<cell>" . utf8_encode(strtoupper(htmlspecialchars($row[proveedor]))) . "</cell>";
    echo "<cell>" . $row[preciocompra] . "</cell>";
    echo "<cell>" . $row[total] . "</cell>";
    echo "<cell>" . $row[sucursal] . "</cell>";
    echo "</row>";
}
echo "</rows>";
        break;
    case 3:
}
mysql_close($db);

function Strip($value)
{
	if(get_magic_quotes_gpc() != 0)
  	{
    	if(is_array($value))
			if ( array_is_associative($value) )
			{
				foreach( $value as $k=>$v)
					$tmp_val[$k] = stripslashes($v);
				$value = $tmp_val;
			}
			else
				for($j = 0; $j < sizeof($value); $j++)
        			$value[$j] = stripslashes($value[$j]);
		else
			$value = stripslashes($value);
	}
	return $value;
}
function array_is_associative ($array)
{
    if ( is_array($array) && ! empty($array) )
    {
        for ( $iterator = count($array) - 1; $iterator; $iterator-- )
        {
            if ( ! array_key_exists($iterator, $array) ) { return true; }
        }
        return ! array_key_exists(0, $array);
    }
    return false;
}
?>